//
// Created by jasonzhuang on 15-12-1.
//

#include <math.h>

#include <algorithm>
#include <ctime>
#include <vector>

#include "SpreadCalc.h"

void calculateSMA(const SMARequest& request, SMAResponse& response) {
  int length = request.series.size();
  int min_l = std::min(length, request.N);
  if (min_l == 0) return;
  for (int i = 0; i < min_l; ++i) {
    double sum = 0.0;
    for (int j = 0; j <= i; ++j) {
      sum += request.series[j];
    }
    response.means[i] = sum / (i + 1);

    double sum_variance = 0.0;
    for (int j = 0; j <= i; ++j) {
      sum_variance += (request.series[j] - response.means[i]) *
                      (request.series[j] - response.means[i]);
    }
    response.stds[i] = sqrt(sum_variance / (i + 1));
  }

  for (int i = min_l; i < length; ++i) {
    double sum = 0.0;
    for (int j = 0; j < min_l; ++j) {
      sum += request.series[i - j];
    }
    response.means[i] = sum / min_l;

    double sum_variance = 0.0;
    for (int j = 0; j < min_l; ++j) {
      sum_variance += (request.series[i - j] - response.means[i]) *
                      (request.series[i - j] - response.means[i]);
    }
    response.stds[i] = sqrt(sum_variance / min_l);
  }
}
